<script setup lang="ts">
import { ref, watch } from 'vue';
import debounce from 'lodash/debounce';

const emit = defineEmits<{
  search: [keyword: string];
}>();

const searchKeyword = ref('');

function handleSearch() {
  emit('search', searchKeyword.value.trim());
}

// 增加防抖处理
const debouncedEmitSearch = debounce((keyword: string) => {
  emit('search', keyword.trim());
}, 400);

function handleInput() {
  // 输入时防抖触发搜索
  debouncedEmitSearch(searchKeyword.value);
}

// 监听搜索关键词变化，当清空时自动触发搜索
watch(searchKeyword, newValue => {
  if (!newValue || newValue.trim() === '') {
    emit('search', '');
  }
});
</script>

<template>
  <div class="mall-search-bar">
    <input
      v-model="searchKeyword"
      class="mall-search-bar__input"
      placeholder="搜索游戏、类型、开发商..."
      @keyup.enter="handleSearch"
      @input="handleInput"
    />
    <button class="mall-search-bar__btn" @click="handleSearch">搜索</button>
  </div>
</template>

<style scoped>
.mall-search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}
.mall-search-bar__input {
  flex: 1;
  height: 48px;
  border: none;
  padding: 0 16px;
  font-size: 16px;
  outline: none;
  color: #333;
  background: #fff;
}
.mall-search-bar__input::placeholder {
  color: #999;
}
.mall-search-bar__btn {
  height: 48px;
  border: none;
  background: #0078d7;
  color: #fff;
  padding: 0 24px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.2s;
}
.mall-search-bar__btn:hover {
  background: #005fa3;
}
</style>
